package francis.utils.servlet;

import java.io.IOException;
import java.io.Writer;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 为减少Service、Model等层对Request\Response的依赖，同时简化Request,Response的参数处理，特建此工具类
 * @author francis
 *
 */
public class ServletUtils {

	/**从request中获取Attributes*/
	public static Map<String, Object> getAttributes(HttpServletRequest request) {
		Map<String, Object> attributes = new HashMap<String,Object>();
		Enumeration<?> e = request.getAttributeNames();
		while (e.hasMoreElements()) {
			String key = (String) e.nextElement();
			attributes.put(key, request.getAttribute(key));
		}
		return attributes;
	}

	/**从request中获取Paramters*/
	public static Map<String, Object> getParameters(HttpServletRequest request) {
		Map<String, Object> parameters = new HashMap<String,Object>();
		Enumeration<?> e = request.getParameterNames();
		while (e.hasMoreElements()) {
			String key = (String) e.nextElement();
			parameters.put(key, request.getParameter(key));
		}
		return parameters;
	}
	
	public static Map<String,Object> parseResponse(HttpServletResponse response) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("writer", getWriter(response));
		return map;
	}
	
	public static Map<String,Object> parseSession(HttpSession session) {
		Map<String,Object> map = new HashMap<String,Object>();
		
		Enumeration<?> e = session.getAttributeNames();
		while (e.hasMoreElements()) {
			String key = (String) e.nextElement();
			map.put(key, session.getAttribute(key));
		}
		
		return map;
	}
	
	/**
	 * 如果要对response设置编码，请务必在此方法调用之前设置好！
	 * @return
	 */
	public static Writer getWriter(HttpServletResponse response) {
		Writer writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return writer;
	}
	
	public static String getRealPath(HttpServletRequest request) {
		return getRealPath(request,"");
	}
	
	public static String getRealPath(HttpServletRequest request,String path) {
		return request.getSession().getServletContext().getRealPath(path);
	}
	
	/**在导出附件前，设置编码以及文件名称**/
	public static void beforeOutput(HttpServletResponse response,String fileName,String charset) {
        response.setHeader("Content-Type", "APPLICATION/OCTET-STREAM;charset=" + charset); 
        response.setHeader("Content-Disposition", "attachment; filename="+ fileName); 
        response.setCharacterEncoding(charset);
	}
	
	/**将Map中的Key-value以setAttribute的方式注入至request中去**/
	public static void putMapToRequest(HttpServletRequest request, Map<String,Object> map) {
		if(map == null || request == null) {
			return;
		}
		for(String key : map.keySet()) {
			request.setAttribute(key, map.get(key));
		}
	}
	
}
